package com.mpgame.config;

import com.mpgame.utils.JwtUtil;
import com.mpgame.common.utils.Log;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
            throws ServletException, IOException {
        
        String token = request.getHeader("Authorization");
        
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            
            if (jwtUtil.validateToken(token)) {
                int accountId = jwtUtil.getAccountIdFromToken(token);
                String username = jwtUtil.getUsernameFromToken(token);
                
                if (accountId > 0 && username != null) {
                    // 设置Spring Security认证
                    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                        accountId, null, Collections.emptyList());
                    SecurityContextHolder.getContext().setAuthentication(auth);
                    
                    // 将用户信息存储到请求属性中
                    request.setAttribute("accountId", accountId);
                    request.setAttribute("username", username);
                    
                    Log.info("JWT认证成功：" + username + " (ID: " + accountId + ")");
                }
            }
        }
        
        filterChain.doFilter(request, response);
    }
}